package com.sx.email.service.impl;

import com.sx.email.Vo.MailVo;
import com.sx.email.service.MailSender;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import java.util.Date;

/**
 * @author shengx
 * @date 2020/5/10 23:20
 */
@Service
public class MailSenderImpl implements MailSender {
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public MailVo sendMail(MailVo mailVo) {
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
            messageHelper.setFrom(mailVo.getFrom());
            messageHelper.setTo(mailVo.getTo().split(","));
            messageHelper.setSubject(mailVo.getSubject());
            messageHelper.setText(mailVo.getText());
            if(!StringUtils.isEmpty(mailVo.getCc())){
                messageHelper.setCc(mailVo.getCc().split(","));
            }
            if(!StringUtils.isEmpty(mailVo.getBcc())){
                messageHelper.setBcc(mailVo.getBcc().split(","));
            }
            if(mailVo.getMultipartFiles() !=null ){
                for (MultipartFile multipartFile : mailVo.getMultipartFiles()) {
                    messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile);
                }
            }
            if(mailVo.getSentDate() == null){
                mailVo.setSentDate(new Date());
                messageHelper.setSentDate(mailVo.getSentDate());
            }
            mailSender.send(messageHelper.getMimeMessage());
            mailVo.setStatus("OK");
        } catch (MessagingException e) {
            e.printStackTrace();
            mailVo.setStatus("FAIL");
            return mailVo;
        }
        return mailVo;
    }
}
